package com.ophiux.cs.api.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ophiux.cs.application.core.AppResultCode;
import com.ophiux.cs.application.core.Request;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.application.core.ResultEnum;
import com.ophiux.cs.application.token.dto.verUserTokenRequest;
import com.ophiux.cs.application.token.dto.verUserTokenResponse;
import com.ophiux.cs.application.token.service.IVerTokenService;
import com.ophiux.utils.common.StringUtil;
import com.ophiux.utils.parser.json.JsonUtils;

@Aspect
@Component
public class CheckTokenAspect {
	final static Logger logger = LoggerFactory.getLogger(CheckTokenAspect.class);

	ThreadLocal<Long> beginTime = new ThreadLocal<Long>();
	@Autowired
	IVerTokenService iVerTokenService;
	
	//json转换
	protected static JsonUtils json = JsonUtils.getIstance();

	@Pointcut("@annotation(checkToken)")
	public void serviceStatistics(CheckToken checkToken) {
	}

	@Around("serviceStatistics(checkToken)")
	public String doBefore(ProceedingJoinPoint joinPoint, CheckToken checkToken) {
		// 记录请求到达时间 
		beginTime.set(System.currentTimeMillis());
		/**
		 * Signature 包含了方法名、申明类型以及地址等信息
		 */
		String class_name = joinPoint.getTarget().getClass().getName();
		String method_name = joinPoint.getSignature().getName();
		logger.info("类名"+class_name+",方法"+method_name+",验证token");
		
		String result = null;
		Object[] method_args = joinPoint.getArgs();
		try {
            try {
            	/**
            	 * 获取方法的参数值数组
            	 */
            	String paramNames = method_args[0]+"";
//            	logger.info("请求参数:"+paramNames);
            	                                                                                                                                                                                                                                             
            	/**
            	 * 1.对参数进行token验证
            	 * 2.判断token是否正确，如果正确，执行后面的操作，如果不正确，则直接返回
            	 * 3.如果正确，执行后面的操作后
            	 */
            	Request req = json.toEntity(paramNames, Request.class);
            	if(req.getHEAD() == null || StringUtil.isEmpty(req.getHEAD().getTOKEN())) {
            		logger.info(method_name+"--->请求参数不合法");
    				result = json.toJson(Result.fail(ResultEnum.requestParamFail.getCode(),ResultEnum.requestParamFail.getMsg()));
            	}else {
            		verUserTokenRequest dto = new verUserTokenRequest();
            		dto.setTOKEN(req.getHEAD().getTOKEN());
            		Result<verUserTokenResponse> verToken = iVerTokenService.verUserToken(dto);
            		if(verToken.getRESULT().equals(Result.RESULT_SUCCESS)) {
            			boolean tokenPd = verToken.getRESPONSE().isResult();
            			if(tokenPd) {//签名Token通过
                			
                			//执行业务方法
        	               	result = (String) joinPoint.proceed();

                		}else {//签名token未通过 
                			logger.info(method_name+"--->token不合法");
            				result = json.toJson(Result.fail(ResultEnum.TokenFail.getCode(),ResultEnum.TokenFail.getMsg()));
                		}
            		}else {
            			result = json.toJson(Result.fail(ResultEnum.requestException.getCode(),ResultEnum.requestException.getMsg()));
            		}
	               	
	               	logger.info(method_name+"--->响应参数："+result);
            	}
			} catch (Throwable e) {
				e.printStackTrace();
				logger.info("验证token异常1",e);
				result = json.toJson(Result.fail(AppResultCode.EXCEPTION,"验证token错误"));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("验证token异常2",e);
			result = json.toJson(Result.fail(AppResultCode.EXCEPTION,"验证token错误"));
		}
		
		return result;
	}

}
